package com.dubbo.protocol.netty;

import com.dubbo.protocol.Client;
import com.dubbo.protocol.bean.Invocation;
import com.dubbo.protocol.http.HttpClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;

public class NettyRpcClient implements Client
{
    @Override
    public Object send(URL url, Invocation invocation)
    {
        ClientHandler clientHandler = new ClientHandler(invocation);

        EventLoopGroup group = new NioEventLoopGroup();

        //创建BootStrap
        Bootstrap b = new Bootstrap();
        try
        {

            b.group(group)  //指定EvenLoopGroup 以处理客户端事件；需要适用于Nio的实现
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(url.getHost(), url.getPort()))

                    .handler(new ChannelInitializer<SocketChannel>()
                    {
                        @Override
                        protected void initChannel(SocketChannel socketChannel)
                        {
                            socketChannel.pipeline().addLast(new ObjectEncoder(),
                                    new ObjectDecoder(Integer.MAX_VALUE , ClassResolvers.cacheDisabled(null)),
                                    clientHandler);
                        }
                    });
            ChannelFuture f = b.connect().sync();
            f.channel().closeFuture().sync();
//            ChannelFuture future = b.connect(url.getHost(), url.getPort()).sync();
//
//            future.channel().closeFuture().sync();


        }
        catch (Exception e)
        {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();

        }
        System.out.println("----------" +clientHandler.getResponse());
        return clientHandler.getResponse();
    }

    @Override
    public Object send(Invocation invocation)
    {
        URL url = null;
        try
        {
            url = new URL("http", "localhost", 8080,"/");
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        return send(url, invocation);
    }

    public static void main(String[] args) throws Exception
    {

        Invocation ivc = new Invocation();
        ivc.setInterfaceName("com.dubbo.service.UserService");
        ivc.setMethodName("findList");
        ivc.setParamsClass(new Class[]{});
        ivc.setParamsValue(new Object[]{});

        new NettyRpcClient().send(ivc);
    }
}
